<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

include_once('sys/itemfunctions.inc');

class EditItemPage {

	private $alerter;
	
	public function __construct() {
		$this->alerter = new Alerter();
	}

	/**
	 * adds extra access checks, dependent on page state
	 */
	function page_inc_check_access($page) {
		check_access("READ");
	}

	/**
	 * appropriate page action interpretations
	 */
	function page_inc_execute_action($action) {
		$this->alerter->add_alert("unknown action");
	}

	/**
	 * execute page logic
	 */
	function page_inc_execute($page) {
		global $filename;
		$THISDIR = $page->directory_tree[$page->dir_depth-1];

		$where = "ITEM.item_id = {$page->id} AND 
				  ITEM.item_type_id = ITEM_TYPE.item_type_id AND 
				  ITEM.author = M1.user_id AND 
				  ITEM.editor = M2.user_id AND 
				  ITEM.item_id = ITEM_IN.item_id AND 
				  ITEM_IN.sub_id = SUB_IN.sub_id AND 
				  SUB_IN.dir_id = {$page->directory_tree[$page->dir_depth-1]['dir_id']}";
		
		$sql = db_query_select(array(array("*"), array("*"), array(), array(), array("*"),
								"M1.nick AS nick_author, M2.nick AS nick_editor"), 
								array("ITEM", "ITEM_TYPE", "MEMBER AS M1, MEMBER AS M2", 
									  "ITEM_IN", "SUB_IN", "DUMMY"), 
								$where);

		$sqlresult = db_do_query($page, $sql);
		
		if (db_num_rows($sqlresult) < 1)
			errorpage(404);
			
		$item = db_fetch_array($sqlresult);
		
		if (!has_access("MODERATE") and !has_access("ADMIN") and !($item['author'] == $_SESSION['user_id']))
			errorpage(5);
			
		$baseTopic = BaseTopic::get_instance($item['extension'], $page->id);
		if ($baseTopic instanceof iEditBody)
		{
			$item['body'] = $baseTopic->get_edit_body();
		}
		if ($baseTopic instanceof iEditEverything)
		{
			$result = $baseTopic->get_edit_everything();
			$item = array_merge($item, $result);
		}
		if ($baseTopic instanceof Link)
		{
			$item['link'] = $baseTopic->get_edit_link();
		}
		if ($baseTopic instanceof Gallery)
		{
			$item['open_for_all'] = $baseTopic->get_open_for_all();
		}
		if ($baseTopic instanceof Event)
		{
			$item['date_start'] = ereg_replace("[^0-9]", "", $item['date_start']);
			$item['date_start_year'] = substr($item['date_start'], 0, 4);
			$item['date_start_month'] = substr($item['date_start'], 4, 2);
			$item['date_start_day'] = substr($item['date_start'], 6, 2);
			$item['date_end_year'] = substr($item['date_end'], 0, 4);
			$item['date_end_month'] = substr($item['date_end'], 4, 2);
			$item['date_end_day'] = substr($item['date_end'], 6, 2);
		}

		if ($_POST['submitted']) {
			// check submitted content
			if (item_page_inc_check_content($_POST, $_FILES, $item['extension'], 0)) {
			
				// if ok, edit db
				
				// derive info stuff
				switch($item['item_type_id']) {
					case ItemType::Topic: // plain topic
					case ItemType::Gallery: // gallery
						$info = strip_tags($_POST['info']);
						break;
					case ItemType::Article: // article
					case ItemType::Download: // download
					case ItemType::Poll: // poll
					case ItemType::News: // news
						$info = strip_tags($_POST['body']);
						$info = substr($info, 0, 50) . ((strlen($info) > 50) ? "..." : "");
						break;
					case ItemType::Ad: // ad
						include_once('sys/regionfunctions.inc');
						$info = region_format(region_get_region_tree($_POST['region']));
						if (ereg("^[0-9]+$", $_POST['game_id'])) {
							$sqlresult = db_do_query($page, db_query_select(array(array('name')), array('GAME'), "game_id = {$_POST['game_id']}"));
							if (db_num_rows($sqlresult) == 1) {
								$g = db_fetch_array($sqlresult);
								$info = "{$g['name']} - $info";
							}
						} else if (strlen($_POST['game_name']) > 0) 
							$info = "{$_POST['game_name']} - $info";
						break;
					case ItemType::Event: // event
						include_once('sys/regionfunctions.inc');
						$date = $_POST['date_start_year'] . (($_POST['date_start_month'] > 9) ? "{$_POST['date_start_month']}" : "0{$_POST['date_start_month']}") . (($_POST['date_start_day'] > 9) ? "{$_POST['date_start_day']}" : "0{$_POST['date_start_day']}") . "000000";
						$info = date_format($date, 0, -1, 1) . " - ";
						$info .= region_format(region_get_region_tree($_POST['region'])); 
						break;
					case ItemType::Link: // link
						$info = substr($_POST['link'], 0, 50) . ((strlen($_POST['link']) > 50) ? "..." : "");
						break;
					case ItemType::Fiche: // spellenfiche
						if ($_POST['game_editor_id'] == "NEW")
							$info = $_POST['editor_name'];
						else {
							$kv = get_keyed_values('game_editor_id', 'editor_name', 'GAME_EDITOR');
							$info = $kv[$_POST['game_editor_id']];
						}
						if ($_POST['game_id'] == "NEW")
							$title = $_POST['game_name'];
						else {
							$kv = get_keyed_values('game_id', 'name', 'GAME');
							$title = $kv[$_POST['game_id']];
						}
						break;
					default:
						$info = "";
						break;
				}
				$info = db_sqlize($info);
				
				$title = $title ? $title : $_POST['title'];
				
				// item update
				$sql = db_query_update(array("editor", "title", "info", "creation", "edit"), 
									   array($_SESSION['user_id'], db_sqlize($title), $info, 
									   "creation", $_POST['mark_new'] ? "NOW(14)" : "edit"), 
									   "ITEM", "item_id = {$item['item_id']}");
				db_do_query($page, $sql);
				
				// type-specific insertion
				switch($item['item_type_id']) {
					case ItemType::Topic: // plain topic
						$sql = "SELECT 0";
						break;
					case ItemType::Article: // article
						$sql = db_query_update(array('body'), array(db_sqlize($_POST['body'])), 
											   "ARTICLE", "item_id = {$item['item_id']}");
						break;
					case ItemType::Link: // link
						$sql = db_query_update(array('link', 'body'), array(db_sqlize($_POST['link']), 
											   db_sqlize($_POST['body'])), "LINK", 
											   "item_id = {$item['item_id']}");
						break;
					case ItemType::Download: // download
						if ($_POST['change_file'])
							$sql = db_query_update(array('body', 'filename'), array(db_sqlize($_POST['body']), db_sqlize($filename)), "DOWNLOAD", "item_id = {$item['item_id']}");
						else
							$sql = db_query_update(array('body'), array(db_sqlize($_POST['body'])), "DOWNLOAD", "item_id = {$item['item_id']}");
						break;
					case ItemType::Poll: // poll
						for ($i = 0; $i < $_POST['num_answers']; $i++) {
							$sql = db_query_update(array('answer'), 
												   array(db_sqlize($_POST["answer_{$i}"])), "POLL_ANSWER", 
												   "answer_id = {$_POST["answer_{$i}_id"]}");
							db_do_query($page, $sql);
						}
						$sql = db_query_update(array('body'), array(db_sqlize($_POST['body'])), 
											   "POLL", "item_id = {$item['item_id']}");	
						break;
					case ItemType::News: // news
						$sql = db_query_update(array('body'), array(db_sqlize($_POST['body'])), 
											   "NEWS", "item_id = {$item['item_id']}");
						break;
					case ItemType::Gallery: // gallery
						$sql = db_query_update(array('body', 'open_for_all'), 
											   array(db_sqlize($_POST['body']), 
											   $_POST['open_for_all'] ? 1 : 0), "GALLERY", 
											   "item_id = {$item['item_id']}");
						break;
					case ItemType::Ad: // ad
						if (ereg("^parent[0-9]+$", $_POST['region'])) { // new region
							db_do_query($page, db_query_insert(array('name'), 
										array(db_sqlize($_POST['region_name'])), "REGION"));
							$region_id = db_insert_id();
							db_do_query($page, db_query_insert(array('parent_region', 'sub_region'), 
										array(substr($_POST['region'], 6), $region_id), "REGION_TREE"));
						} else
							$region_id = $_POST['region'];
						
						if ($_POST["game_id"] == "NEW") {
							db_do_query($page, db_query_insert(array('name'), 
										array(db_sqlize($_POST["game_name"])), "GAME"));
							$game_id = db_insert_id();
							db_do_query($page, db_query_insert(array('game_id', 'game_type_id'), 
										array($game_id, $_POST["game_type"]), "GAME_OF_TYPE"));
						} else if ($_POST['game_id'] == "NONE")
							$game_id = "NULL";
						else
							$game_id = $_POST["game_id"];
							
						$sql = db_query_update(array('game_id', 'region_id', 'body', 'seek'), 
											   array($game_id, $region_id, db_sqlize($_POST['body']), 
											   ($_POST['seek'] == "GZ") ? 1 : 0), "AD", 
											   "item_id = {$item['item_id']}");
						break;
					case ItemType::Event: // event
						if (ereg("^parent[0-9]+$", $_POST['region'])) { // new region
							db_do_query($page, db_query_insert(array('name'), 
										array(db_sqlize($_POST['region_name'])), "REGION"));
							$region_id = db_insert_id();
							db_do_query($page, db_query_insert(array('parent_region', 'sub_region'), 
										array(substr($_POST['region'], 6), $region_id), "REGION_TREE"));
						} else
							$region_id = $_POST['region'];
						
						$date = $_POST['date_start_year'] . (($_POST['date_start_month'] > 9) ? "{$_POST['date_start_month']}" : "0{$_POST['date_start_month']}") . (($_POST['date_start_day'] > 9) ? "{$_POST['date_start_day']}" : "0{$_POST['date_start_day']}") . "000000";	

						$enddate = "NULL";
						if ($_POST['date_end_day'])
							$enddate = $_POST['date_end_year'] . (($_POST['date_end_month'] > 9) ? "{$_POST['date_end_month']}" : "0{$_POST['date_end_month']}") . (($_POST['date_end_day'] > 9) ? "{$_POST['date_end_day']}" : "0{$_POST['date_end_day']}") . "000000";
							
						$sql = db_query_update(array('region_id', 'description', 'link', 'date_start', 'multiple_days', 'date_end'), array($region_id, db_sqlize($_POST['description']), db_sqlize($_POST['link']), $date, $_POST['multiple_days'] ? 1 : 0, $enddate), "EVENT", "item_id = {$item['item_id']}");

						if ($_POST['archive'])
							db_do_query($page, db_query_insert(array('item_id', 'date_start', 'multiple_days', 'date_end', 'title'), 
										array($item['item_id'], $item['date_start'], 
										$item['multiple_days'], $item['date_end'], 
										db_sqlize(db_desqlize($item['title']))), "EVENT_EDITION"));
						break;
					case ItemType::Fiche: // spellenfiche
						
						if ($_POST["game_id"] == "NEW") {
							db_do_query($page, db_query_insert(array('name'), 
										array(db_sqlize($_POST["game_name"])), "GAME"));
							$game_id = db_insert_id();
							db_do_query($page, db_query_insert(array('game_id', 'game_type_id'), 
										array($game_id, $_POST["game_type"]), "GAME_OF_TYPE"));
						} else
							$game_id = $_POST["game_id"];
						
						if ($_POST["game_editor_id"] == "NEW") {
							db_do_query($page, db_query_insert(array('editor_name', 'editor_link'), 
										array(db_sqlize($_POST["editor_name"]), 
										db_sqlize($_POST["editor_link"])), "GAME_EDITOR"));
							$editor_id = db_insert_id();
						} else
							$editor_id = $_POST["game_editor_id"];

						$sql = db_query_update(array('game_id', 'game_editor_id', 'image_link', 'url',
													 'description', 'genre', 'rules', 'players', 
													 'expansions', 'requirements', 'price', 'languages',
													 'did_you_know', 'forum_link'), 
											   array($game_id, $editor_id, 
													 $filename ? db_sqlize($filename) : 'image_link', 
													 db_sqlize($_POST['url']), 
													 db_sqlize($_POST['description']), 
													 db_sqlize($_POST['genre']), 
													 db_sqlize($_POST['rules']), 
													 db_sqlize($_POST['players']), 
													 db_sqlize($_POST['expansions']), 
													 db_sqlize($_POST['requirements']), 
													 db_sqlize($_POST['price']), 
													 db_sqlize($_POST['languages']), 
													 db_sqlize($_POST['did_you_know']), 
													 $_POST['forum_link']), 
												"GAME_FICHE", "item_id = {$item['item_id']}");
						
						db_do_query($page, db_query_update(array('link'), 
													array(db_sqlize("{$page->dir_path}/{$item['item_id']}.fiche")),
													"GAME", "game_id = $game_id"));

						break;
					default:
						errorpage(8);
						break;
				}
				
				db_do_query($page, $sql);
				
				// subset insertion
				if ($_POST['sub_id'] == "NEW") {
					$sql = db_query_insert(array('sub_title'), array(db_sqlize($_POST['new_subset'])), 
										   "SUBSET");
					db_do_query($page, $sql);
					$sub_id = db_insert_id();
					$sql = db_query_insert(array('dir_id', 'sub_id', 'sub_title'), 
										   array($THISDIR['dir_id'], 
										   $sub_id, db_sqlize($_POST['new_subset'])), "SUB_IN");
					db_do_query($page, $sql);
				} else {
					$sub_id = $_POST['sub_id'];
				}

				// in_sub update
				$sql = db_query_update(array('sub_id'), array($sub_id), "ITEM_IN", "item_id = {$item['item_id']} AND sub_id = {$item['sub_id']}");
				db_do_query($page, $sql);
				
				// readings reset
				if ($_POST['mark_new']) {
					$sql = db_query_delete("HAS_READ", "item_id = {$page->id}");
					db_do_query($page, $sql);
				}
				$itemType = new ItemType();	
				redirect($page->dir_path . "/{$item['item_id']}." . $itemType->get_type_string($item['item_type_id']));
			}
		}
		
		$page->content['title'] = ucfirst($item['name']) ." #{$item['item_id']} aanpassen";
		
		item_form($page, $item);
	}


	/**
	 * dress up page content using skin stuff
	 */
	function page_inc_dress($page) {
		print_form($page, $page->content['form']);
		// TODO previews
	}
}

?>